<?php

/**
 * doctor actions.
 *
 * @package    docplus.co.za
 * @subpackage doctor
 * @author     Fox Matuku
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class doctorActions extends gfFrontendActions
{
    /**
     * Executes account action
     *
     * @param sfRequest $request A request object
     */
    public function executeAccount(sfWebRequest $request)
    {        
    }

    /**
     * Executes publicProfile action
     *
     * @param sfRequest $request A request object
     */
    public function executePublicProfile(sfWebRequest $request)
    {
        // set the current route
        $this->getUser()->setCurrentRoute("profile_public");
        
        $this->doctor = DoctorTable::getInstance()->findOneByUserSlug($request['slug']);
        $this->doctorAverageRating = DoctorRatingTable::getInstance()->updateOrCreateByDoctorIdAndRatingValue($this->doctor->getId(), 0);
        $this->form = new myAppointmentReasonForm();
        
        // fetch the question answer comment form
        $this->_getAnswerCommentForm();
    }

    /**
     * Executes search action
     *
     * @param sfRequest $request A request object
     */
    public function executeSearch(sfWebRequest $request)
    {
        $this->getUser()->setCurrentRoute("static_find_a_doctor");
        
        $defaults = array();
        if ($request->hasParameter('city_id'))
        {
            $defaults['city_id'] = $request->getParameter('city_id');
        }

        if ($request->hasParameter('speciality_id'))
        {
            $defaults['speciality_id'] = $request->getParameter('speciality_id');
        }

        $this->form = new myDoctorSearchForm();
        $this->form->setDefaults($defaults);
        if ($request->isMethod('post'))
        {
            $this->form->bind($request->getParameter($this->form->getName()));
            if ($this->form->isValid())
            {
                try
                {
                    // grab my doctors and make them available to my Members
                    $this->doctors = DoctorTable::getInstance()->retrieveBySearch($this->form->getValues());
                }
                catch (Exception $e)
                {
                    throw $e;
                    // invoke the event here so we get the error via email
                }
            }
        }
        else
        {
            $this->doctors = DoctorTable::getInstance()->retrieveBySearch($defaults);
        }
    }

    /**
     * Executes register action
     *
     * @param sfRequest $request A request object
     */
    public function executeRegister(sfWebRequest $request)
    {
        $this->form = new DoctorForm();
    }

    /**
     * Executes registerStepOne action
     *
     * @param sfRequest $request A request object
     */
    public function executeRegisterStepOne(sfWebRequest $request)
    {
        $this->form = new DoctorForm();
        if ($request->isMethod('post'))
        {
            $this->form->bind($request->getParameter($this->form->getName()));
            if ($this->form->isValid())
            {
                try
                {
                    $doctor = $this->form->save();
                    //proceed to step two
                    $this->redirect("/doctor-register-step-two/" . $doctor->getId());
                }
                catch (Exception $e)
                {
                    // invoke the event here so we get the error via email
                }
            }
        }
    }

    /**
     * Executes registerStepTwo action
     *
     * @param sfRequest $request A request object
     */
    public function executeRegisterStepTwo(sfWebRequest $request)
    {
        $this->doctor = DoctorTable::getInstance()->find($request->getParameter("doctor_id", null));
        $this->forward404Unless($this->doctor);

        $contact = new Contact();
        $contact->setUserId($this->doctor->getUserId());

        $this->form = new DoctorContactForm($contact);

        if ($request->isMethod('post'))
        {
            $this->form->bind($request->getParameter($this->form->getName()));

            if ($this->form->isValid())
            {
                $contact = $this->form->save();

                // set the mobile activation code
                $contact->setMobileActivationCode(rand(10000, 99999));
                $contact->save();

                // send the mobile activation code here...
                // proceed to step three
                $this->redirect("/doctor-register-step-three/" . $contact->getId() . "/stay");
            }
        }
    }

    /**
     * Executes registerStepThree action
     *
     * @param sfRequest $request A request object
     */
    public function executeRegisterStepThree(sfWebRequest $request)
    {
        $this->command = $request->getParameter("command", "stay");
        $this->contact = ContactTable::getInstance()->findOneById($request->getParameter("contact_id", null));
        $this->forward404Unless($this->contact);
        $this->form = new MobileConfirmationForm(array('id' => $this->contact->getId()));
        if ($request->isMethod('post'))
        {
            $this->form->bind($request->getParameter($this->form->getName()));
            if ($this->form->isValid())
            {
                //activate the user
                $user = $this->contact->getUser();
                $user->setIsActive(true);
                $user->save();

                // seems everything has gone smoothly...so we can as well log them in :)
                $this->getUser()->signin($user, $this);

                $this->getUser()->setFlash('notice', 'Congratulations, you\'ve successfully signed up for an account on DocPlus! Please wait a moment while you\'re being redirected back to the home page.');

                //proceed to confirmation
                $this->redirect("/doctor-register-step-three/" . $this->contact->getId() . "/done");
            }
        }
    }

    /**
     * Executes profile action
     *
     * @param sfRequest $request A request object
     */
    public function executeProfile(sfWebRequest $request)
    {
        $this->forward404Unless($this->getUser()->getDpUser());
        $this->doctor = DoctorTable::getInstance()->findOneByUserId($this->getUser()->getUserId());
        $this->form = new myDoctorForm($this->doctor);
        if ($request->isMethod('post'))
        {
            $this->form->bind($request->getParameter($this->form->getName()));
            if ($this->form->isValid())
            {
                try
                {
                    $doctor = $this->form->save();
                    $this->getUser()->setFlash('notice', 'The item was updated successfully.');

                    $this->redirect("/doctor-profile");
                }
                catch (Exception $e)
                {
                    // invoke the event here so we get the error via email
                }
            }
            else
            {
                foreach ($this->form as $field)
                {
                    echo $field->renderLabel() . " " . $field->renderError() . "<br />";
                }
                die($this->form->renderGlobalErrors());
            }
        }
    }

    /**
     * Executes practiceDetails action
     *
     * @param sfRequest $request A request object
     */
    public function executePracticeDetails(sfWebRequest $request)
    {
        $this->forward404Unless($this->getUser()->getDpUser());
        $this->doctor = DoctorTable::getInstance()->findOneByUserId($this->getUser()->getUserId());
        $contact = ContactTable::getInstance()->findOneByUserId($this->getUser()->getUserId());

        $this->form = new myPracticeDetailsForm($this->doctor, array("contact" => $contact));
        if ($request->isMethod('post'))
        {
            $this->form->bind($request->getParameter($this->form->getName()));
            if ($this->form->isValid())
            {
                try
                {
                    $doctor = $this->form->save();
                    $this->getUser()->setFlash('notice', 'The item was updated successfully.');

                    $this->redirect("/doctor-practice-details");
                }
                catch (Exception $e)
                {
                    // invoke the event here so we get the error via email
                }
            }
            else
            {
                foreach ($this->form as $field)
                {
                    echo $field->renderLabel() . " " . $field->renderError() . "<br />";
                }
                die($this->form->renderGlobalErrors());
            }
        }
    }

    /**
     * Executes credentials action
     *
     * @param sfRequest $request A request object
     */
    public function executeCredentials(sfWebRequest $request)
    {
        $dpUser = $this->getUser()->getDpUser();
        $this->forward404Unless($dpUser);
        $this->form = new myCredentialsForm(array(
                "user_id" => $dpUser->getId(),
                "email" => $dpUser->getEmail()),
                array("user" => $dpUser)
        );

        if ($request->isMethod('post'))
        {
            $this->form->bind($request->getParameter($this->form->getName()));
            if ($this->form->isValid())
            {
                try
                {
                    $doctor = $this->form->save();
                    $this->getUser()->setFlash('notice', 'The item was updated successfully.');
                    $this->redirect("/doctor-credentials");
                }
                catch (Exception $e)
                {
                    // invoke the event here so we get the error via email
                }
            }
        }
    }

    /**
     * Executes education action
     *
     * @param sfRequest $request A request object
     */
    public function executeEducation(sfWebRequest $request)
    {
        
    }

    /**
     * Executes locations action
     *
     * @param sfRequest $request A request object
     */
    public function executeLocations(sfWebRequest $request)
    {
        
    }

    /**
     * Executes notifications action
     *
     * @param sfRequest $request A request object
     */
    public function executeNotifications(sfWebRequest $request)
    {
        
    }

    /**
     * Executes schedule action
     *
     * @param sfRequest $request A request object
     */
    public function executeSchedule(sfWebRequest $request)
    {
        $this->getUser()->setCurrentRoute("doctor_schedule");
        if ($this->getUser()->getType() == "Doctor")
        {
            //gfToolkit::debug($this->getUser()->getId());
            $this->doctorId = $this->getUser()->getDoctor()->getId();
        }
        else
        {
            $this->doctorId = $this->getUser()->getDoctorId();
        }
    }

    /**
     * Executes timeSlots action
     *
     * @param sfRequest $request A request object
     */
    public function executeTimeSlots(sfWebRequest $request)
    {
        die(json_encode(DoctorTimeSlotTable::getInstance()->retrieveByDoctorId($request->getParameter("doctor_id", null))));
    }

    /**
     * Executes rate action
     *
     * @param sfRequest $request A request object
     */
    public function executeRate(sfWebRequest $request)
    {
        if ($request->hasParameter("doctor_id") && $request->hasParameter("rating_value"))
        {
            $this->doctorAverageRating = DoctorRatingTable::getInstance()->updateOrCreateByDoctorIdAndRatingValue($request->getParameter("doctor_id"), $request->getParameter("rating_value"));
            $this->doctor = DoctorTable::getInstance()->findOneById($request->getParameter("doctor_id"));
        }
    }

    /**
     * Executes averageRating action
     *
     * @param sfRequest $request A request object
     */
    public function executeRatingAverage(sfWebRequest $request)
    {
        if ($request->hasParameter("doctor_id"))
        {
            $this->doctorAverageRating = DoctorRatingTable::getInstance()->updateOrCreateByDoctorIdAndRatingValue($request->getParameter("doctor_id"), 0);
            $this->doctor = DoctorTable::getInstance()->findOneById($request->getParameter("doctor_id"));
        }
        else
        {
            $this->doctorAverageRating = DoctorRating();
            $this->doctor = new Doctor();
        }
    }

    public function executeAnswers(sfWebRequest $request)
    {
        $this->getUser()->setCurrentRoute("doctor_answers");
        
        $user = GfUserTable::getInstance()->findOneBySlug($request['slug']);
        $this->similarQuestions = DoctorTable::getInstance()->retrieveForConnections();
        
        $this->doctor = DoctorTable::getInstance()->findOneByUserSlug($request['slug']);

        // fetch the answer comment form
        $this->_getAnswerCommentForm();
    }

}
